package com.Arsanesia.TempleRush.Controllers;

import com.Arsanesia.TempleRush.Enumeration.TempleRushMusic;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Disposable;

public class MusicManager implements Disposable, StreamManager{
	private Music playedMusic;
	private float volume = 1f;
	private boolean enabled = true;
	private TempleRushMusic m;
	
	public MusicManager(){
		enabled = true;
		volume = 1f;
	}
	
	


	@Override
	public <Stream> void play(Stream stream) {
		if(stream.getClass() == TempleRushMusic.class){
			boolean issame = m == (TempleRushMusic)stream;
			m = (TempleRushMusic) stream;
			
			if(!enabled) return;//prevent  playing music if not enabled
//			FileHandle musicfile = Gdx.files.internal(m.getFileName()) ;
//			playedMusic = Gdx.audio.newMusic(musicfile);
			
			if(playedMusic != null && !issame) 	{			
				//stop any other music
				stop();
			}
			//prevent stoping the same music that has been played
			
			if(playedMusic == null){
				FileHandle musicfile = Gdx.files.internal(m.getFileName()) ;
				playedMusic = Gdx.audio.newMusic(musicfile);

				playedMusic.setVolume(volume);
				playedMusic.setLooping(true);
				playedMusic.play();
			}

		}
	}


	@Override
	public void stop() {
		if(playedMusic!=null){
//			playedMusic.stop();
			playedMusic.dispose();
			playedMusic = null;
		}
		
	}

	@Override
	public void dispose() {
		
		stop();
//		if(playedMusic != null)
//			playedMusic.dispose();
	}


	@Override
	public void setEnabled(boolean _enabled) {
		this.enabled = _enabled;
		if(!enabled){
			stop();
		}
		
	}


	@Override
	public boolean isEnabled() {
		return enabled;
	}


	@Override
	public void toggleEnable() {
		this.enabled = !enabled;
		if(enabled){
			play(m);
		}
		else
			stop();
	}
}
